/* eslint-disable no-param-reassign */
/* eslint-disable eqeqeq */
import { message } from 'antd';
import moment from 'moment';
import {
  getList,
  queryDictItemsByCodes,
  payApply,
  cancleApply,
  handleBillOk,
  updateBill,
  getDetailList,
  getBillContent,
  getProgress,
  markPaid,
  checkHasTask,
  checkRtnState,
  getInsNoBillEmpDet,
  getAccuNoBillEmpDet,
} from '@/services/socialinsurancehadpay';
import * as service from '@/services/socket';

export default {
  state: {
    payFeesWay: [],
    payStateArr: [],
    rtnState: [],
    bizeType: [],
    batchQuery: {},
    formFieldsValue: {},
    expandForm: false,
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    pageDetailData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    id: '',
    detailRtnState: '',
    corpId: '',
    insBillDetail: {},
    accoStatusList: [],
    progressPercent: 0,
    isFirstClose: true,
    paidData: [],
    stateMap: ['', 'default', 'warning', 'success'], // 第一项用不到
    isHasTask: false,
    batchNo: '',
    isUpdate: '',
    noDataSource: [],
    noCmTotal: 1,
    showProgress: false,
    resultInfo: {
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
  },
  effects: {
    *checkRtnState({ payload }, { call }) {
      const res = yield call(checkRtnState, payload);
      return res;
    },
    *checkHasTask(_, { call, put }) {
      const res = yield call(checkHasTask);
      if (res.success) {
        if (res.data[0]) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: true,
              batchNo: res.data[0].batchNo,
              isUpdate: res.data[0].isUpdate,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: false,
            },
          });
        }
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *markPaid({ payload }, { call }) {
      const res = yield call(markPaid, payload);
      return res;
    },
    *getProgress({ payload }, { call, put }) {
      const res = yield call(getProgress, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            progressPercent: res.data.successProp,
          },
        });
      } else {
        // 服务端异常
        message.warning(`${res.message || '查询失败'}`);
      }
      // callback()
      return res;
    },
    *queryDictCodes({ payload }, { call, put }) {
      const res = yield call(queryDictItemsByCodes, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            bizeType: res.data.BIZ_INS_TYPE.concat(res.data.BIZ_WEAL_TYPE),
            accoStatusList: res.data.ACCO_STATUS || [],
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *getBillDto({ payload }, { call, put }) {
      const res = yield call(getBillContent, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            insBillDetail: res.data,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *fetchDetail({ payload }, { call, put }) {
      const response = yield call(getDetailList, payload); // 请求
      const { currentPage, pageSize } = payload.pageArg;
      if (response.success) {
        yield put({
          type: 'getDetailList', // 处理后台返回数据
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    // 更新批量任务数据

    *updateIndexBatchTask({ payload }, { select, put }) {
      const { formFieldsValue } = yield select(state => state.socialinsurancehadpay);
      const {
        pagination: { current, pageSize },
      } = yield select(state => state.socialinsurancehadpay.pageData);

      const tempValues = {};
      Object.keys(formFieldsValue).forEach(key => {
        if (key === 'billMonth' && formFieldsValue.billMonth) {
          tempValues.queryStartTime = moment(formFieldsValue.billMonth[0]).format('YYYYMM');
          tempValues.queryEndTime = moment(formFieldsValue.billMonth[1]).format('YYYYMM');
        } else if (formFieldsValue[key] && formFieldsValue[key].key) {
          tempValues[key] =
          formFieldsValue[key].key === undefined || formFieldsValue[key].key === null
              ? null
              : formFieldsValue[key].key;
        } else {
          tempValues[key] = formFieldsValue[key] === undefined ? null : formFieldsValue[key].trim();
        }
      });

      const pageArg = {
        currentPage: current,
        pageSize,
      };
      const params = { pageArg, ...tempValues };

      if (payload.successProp === 100) {
        yield put({
          type: 'fetchList',
          payload: params,
        });
        if (payload.errorCount > 0) {
          message.success('有错误数据，请联系运维人员');
        } else {
          message.success('操作成功！');
        }
        yield put({
          type: 'updateModelData',
          payload: {
            showProgress: false,
            progressPercent: payload.successProp,
          },
        });
      }
      yield put({
        type: 'updateModelData',
        payload: {
          progressPercent: payload.successProp,
        },
      });
    },

    *updateBill({ payload }, { call, put }) {
      const response = yield call(updateBill, payload);

      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data.batchId,
            progressPercent: 0,
          },
        });
        if (response.data && response.data.successProp !== 100) {
          yield put({
            type: 'updateModelData',
            payload: {
              showProgress: true,
            },
          });
          yield call(service.socketChannel, {
            type: 'sub',
            data: {
              to: response.data && (response.data.batchId || response.data),
              type: 'updateInsBillFile',
            },
          });
        } else {
          yield put({
            type: 'updateIndexBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
      // if (res.success) {
      //   // message.success('操作成功！');
      //   yield put({
      //     type: 'updateModelData',
      //     payload: {
      //       isFirstClose: true,
      //     },
      //   });
      // } else {
      //   message.warning(res.message || '服务端错误');
      // }
      // return res;
    },
    *handleBillOk({ payload }, { call, put }) {
      const res = yield call(handleBillOk, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            isFirstClose: true,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *cancleApply({ payload }, { call }) {
      const res = yield call(cancleApply, payload);
      if (res.success) {
        message.success('撤销成功！');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *payApply({ payload }, { call }) {
      const res = yield call(payApply, payload);
      if (res.success) {
        message.success('申请成功！');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *queryDictItemsByCodes({ payload }, { call, put }) {
      const res = yield call(queryDictItemsByCodes, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            payFeesWay: res.data.PAY_FEES_WAY || [],
            payStateArr: res.data.PAY_STATE || [],
            rtnState: res.data.RTN_STATE || [],
            bizeType: res.data.BIZ_INS_TYPE || [],
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getList, payload); // 请求
      const { currentPage, pageSize } = payload.pageArg;
      if (response.success) {
        yield put({
          type: 'getList', // 处理后台返回数据
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    *fetchNoBillEmpDet({ payload }, { call, put }) {
      const { type, inParam } = payload;
      const response = yield call(+type === 1 ? getInsNoBillEmpDet : getAccuNoBillEmpDet, inParam); // 请求
      if (response.success) {
        yield put({
          type: 'getNoList', // 处理后台返回数据
          payload: { data: response.data },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
  },
  reducers: {
    // 设置页签状态
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      if (list) {
        list.forEach((item, i, arr) => {
          state.payStateArr.forEach(c => {
            if (item.payState == c.itemCode) {
              arr[i].payState = c.itemName;
            }
          });
        });
      }
      return {
        ...state,
        pageData: {
          list,
          pagination: {
            total: data.totalCount,
            current: currentPage,
            pageSize,
          },
        },
      };
    },
    getDetailList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageDetailData: {
          list,
          pagination: {
            total: data.totalCount,
            current: currentPage,
            pageSize,
          },
        },
      };
    },
    getNoList(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        noDataSource: data.pageRecords,
        noCmTotal: data.totalCount,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { showProgress, resultInfo } = state;
      showProgress = true;
      if (payload.successProp === 100) {
        resultInfo.errorParams = {
          batNo: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        showProgress = false;
      }
      return {
        ...state,
        showProgress,
        progressPercent: payload.successProp,
        resultInfo,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'updateInsBillFile':
            dispatch({
              type: 'updateIndexBatchTask',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
          default:
        }
      });
    },
  },
};
